package com.github.itdachen.auth.oauth.rbac.storage.permission;

import com.alibaba.fastjson2.JSON;
import com.github.itdachen.auth.oauth.rbac.constants.RedisKeyConstant;
import com.github.itdachen.auth.oauth.rbac.handler.IAppPermissionHandler;
import com.github.itdachen.auth.oauth.rbac.storage.IAppPermissionStorageHandler;
import com.github.itdachen.framework.context.permission.PermissionInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * RBAC 鉴权策略
 *
 * @author 王大宸
 * @date 2025-02-18 15:40
 */
@Service
public class RbacAppPermissionStorageStorageStrategy implements IAppPermissionStorageHandler {


    private final IAppPermissionHandler appPermissionHandler;
    private final StringRedisTemplate stringRedisTemplate;

    public RbacAppPermissionStorageStorageStrategy(IAppPermissionHandler appPermissionHandler,
                                                   StringRedisTemplate stringRedisTemplate) {
        this.appPermissionHandler = appPermissionHandler;
        this.stringRedisTemplate = stringRedisTemplate;
    }


    @Override
    public List<PermissionInfo> findAppPermissions() {
        final String key = RedisKeyConstant.REDIS_KEY_ALL_PERMISSIONS;
        // 从 Redis 中获取权限信息
        String s = stringRedisTemplate.opsForValue().get(key);
        if (s == null || StringUtils.isBlank(s) || "[]".equals(s)) {
            List<PermissionInfo> permissions = appPermissionHandler.permissions();
            s = JSON.toJSONString(permissions);
            stringRedisTemplate.opsForValue().set(key, s, RedisKeyConstant.APP_PERMISSIONS_TIME_OUT, TimeUnit.HOURS);
            return permissions;
        }
        if (StringUtils.isEmpty(s)) {
            return new ArrayList<>();
        }
        return JSON.parseArray(s, PermissionInfo.class);
    }

}
